// 获取应用实例
const app = getApp()
const ipconfig = app.globalData.ipconfig;
var utils = require('../../utils/util')
var http = require('../../utils/http')
Page({
	data: {
		//分页信息
		queryInfo: {
			//页码
			pageNumber: 1,
			//页数
			pageSize: 10,
			//搜索字段
			queryString: ''
		},
		//表格数据
		tableList: [],
		//上拉时时候还有更多要展示的数据
		hasMoreDate: true,
		//首页展示图片
        imageURL: '',
        //登录按钮显示与隐藏
        loginbtn: true
    },

    //登录
	login() {
		let that = this;
        // 登录
		wx.login({
			success(res1) {
				if (res1.code) {
                    //发起网络请求
                    wx.request({
                      url: 'http://'+ ipconfig + ":8080/mini/login",
                      method:"GET",
                      data:{code:res1.code},
                      success(res){
                        const {flag,data,message} = res.data;
                        console.log("flag,data,message",res);
                        const msg = message.split("::")
                        if (!flag) {
                            wx.showToast({
                                title: msg[0],
                                icon: 'fail',
                                duration: 2000
                            })
                        }
                        if(res.statusCode == 400){
                            that.register(msg[1],that)
                        }else{
                            //将登录信息存到本地
                            wx.setStorageSync('token', `${data.tokenHead} ${data.token}`);
                            wx.setStorageSync('userInfo', data.userInfo);
                            wx.setStorageSync('openId', data.openid)
                            that.setData({
                                'loginbtn':utils.hasToken()
                            })
                            //判断是否需要完善信息
                            if (data.userInfo.password == null) {
                                wx.navigateTo({
                                    url: '/pages/login/login',
                                })
                            }
                            that.findPage()
                        }
                        
                      },
                      fail(err){
                        console.log('请求失败',err)
                      }
                    })
					
				} else {
					console.log('登录失败！' + res.errMsg)
				}
            },
            fail:function(res){
                console.log("请求失败",res);
            }
		});
    },
    bindblur(e){
        this.setData({
            'queryInfo.pageNumber':1,
            'queryInfo.queryString':e.detail.value
        })
        this.findPage("数据加载中。。。")
        
    },

    register(openId,that){
        wx.request({
            url: 'http://' + ipconfig + ':8080/mini/register',
            method: 'GET',
            data: {openId:openId},
            success: function (res) {
                console.log(res);
                that.login()
            },
            fail: function (err) {
                console.log("请求失败",err);
            }
        })
    },


	// 获取分页数据，massage是提示语
	findPage(message) {
		//加载提示
		if (!this.data.hasMoreDate) {
            wx.showNavigationBarLoading();
            wx.showToast({
                title: message,
                icon: 'loading',
                duration: 1000
            })
        }
        const that = this;
        const token = wx.getStorageSync('token')
        if (token != '') {
            console.log(this.data.queryInfo);
            http.post("/news/findPage",this.data.queryInfo,res=>{
                
                if (res.statusCode == 401) {
                    //token已过期
                    that.setData({
                        loginbtn:false
                    })
                    wx.clearStorageSync()
                    that.findPage("数据加载中。。。")
                }else{
                    //将原有的结果列表定义为临时数组
                    let temp = this.data.tableList;
                    //将新的结果接收
                    let result1 = res.data.rows;
                    //数据格式化
                    let result = result1.map((item, index) => {
                        //时间格式化
                        if (item != null) {
                            item.createTime = utils.formatTime(item);
                        }
                        const content = item.content
                        item.content = utils.toMarkdown(item.content)
                        //从文章中提取图片链接
                        return Object.assign(item, {
                            'imageURL': utils.get_url(content)
                        })
                    })
                    utils.pageHelper(result,temp,this)
                    console.log(this.data.tableList);
                }                    
            })
        }else{
            http.postNoHeader("/news/findPage",this.data.queryInfo,res=>{
                //将原有的结果列表定义为临时数组
                let temp = this.data.tableList;
                //将新的结果接收
                let result1 = res.data.rows;
                //数据格式化
                let result = result1.map((item, index) => {
                    //时间格式化
                    if (item != null) {
                        item.createTime = utils.formatTime(item);
                    }
                    const content = item.content
                    item.content = utils.toMarkdown(item.content)
                    //从文章中提取图片链接
                    return Object.assign(item, {
                        'imageURL': utils.get_url(content)
                    })
                })
                utils.pageHelper(result,temp,this)             
            })
        }
		
	},
   
    //跳转到详情页
	toarticleDetails(event) {
        let item = event.currentTarget.dataset.item
        Object.assign(item,{'topicType':'new'})
		wx.navigateTo({
			url: '/pages/articleDetails/articleDetails?item=' + encodeURIComponent(JSON.stringify(item)),
		})
	},
	
	onLoad: function (options) {
		this.findPage('加载中....');
	},
	
	onShow: function () {
        this.getTabBar().init();
        this.setData({
            'loginbtn':utils.hasToken()
        })
	},
	
	onPullDownRefresh: function () {
        this.setData({
            'queryInfo.pageNumber':1,
            tableList:[]
        })
		this.findPage('数据刷新中....');

	},
	onReachBottom: function () {
		this.findPage('数据加载中....')
	}
})